package com.whut.www.file_storage.activity;

import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.whut.www.file_storage.R;

import java.io.File;

/**
 * 通过SQLiteDatabase.openDatabase(String path, CursorFactory factory, int flags)可以打开或创建数据库
 * path数据结构的路径,flags数据库操作权限
 * <p>
 * cursor中必须有_id字段,否则使用select id as _id将id转换为_id,此时cursor中就没有id这一列了,而是_id.
 * 从cursor中获取的数据只能是cursor查询过的字段
 * 查询数据后cursor的游标停留在-1的位置,此时取值会抛出异常,应先通过cursor.moveToNext()移动游标在进行取值
 * mCursorAdapter.changeCursor(null)会替换一个新的cursor,并将旧的cursor关闭
 * mCursorAdapter.swapCursor(cursor)只替换cursor,不关闭旧的cursor
 */
public class SQLiteOpenDataBaseActivity extends AppCompatActivity {
    private SimpleCursorAdapter mCursorAdapter;
    private SQLiteDatabase mSqLiteDatabase;
    private ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite_data_base);
        //初始化数据库
        initDataBase();
        //初始化控件
        initView();
        //获取数据
        loadData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mCursorAdapter.changeCursor(null)会替换一个新的cursor,并将旧的cursor关闭
        //mCursorAdapter.swapCursor(cursor)只替换cursor,不关闭旧的cursor
        //关闭cursor
        mCursorAdapter.changeCursor(null);
        //关闭数据库
        mSqLiteDatabase.close();
        //取消上下文菜单
        unregisterForContextMenu(mListView);
    }

    private void initDataBase() {
        //获取数据库的存储目录
        String dataBasePath = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
                .getAbsolutePath() + File.separator + "android_manual.db";
        //打开数据库
        mSqLiteDatabase = SQLiteDatabase.openDatabase(dataBasePath, null, SQLiteDatabase
                .OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);
/*
SQLiteDatabase提供了几个静态方法来打开一个文件对应的数据库。
public	static  SQLiteDatabase  openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
	flags, DatabaseErrorHandler errorHandler)
public	static  SQLiteDatabase  openDatabase(String path, SQLiteDatabase.CursorFactory factory, int
	flags)
public	static  SQLiteDatabase  openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory
	factory, DatabaseErrorHandler errorHandler)
public	static  SQLiteDatabase  openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory
factory)
【备注：】以上方法均可打开or创建数据库
	1、参数中的path代表着数据库的路径（如果是在默认路径/data/data/<package_name>/databases/下，则这里只需要提供数据库名称）最好提供完整的路径;
	2、factory代表着在创建Cursor对象时，使用的工厂类，如果为null的话，则使用默认的工厂（这里我们可以实现自己的工厂进行某些数据处理）;
	3、flags代表的是创建表时的一些权限设置，多个权限之间用|分隔:
		OPEN_READONLY ：代表的是以只读方式打开数据库（常量值为：1）
		OPEN_READWRITE：代表以读写方式打开数据库（常量值为：0）
		CREATE_IF_NECESSARY：当数据库不存在时创建数据库
*/
    }

    private void initView() {
        mListView = (ListView) findViewById(R.id.listView);
        TextView textView = (TextView) findViewById(R.id.tv_empty);
        mListView.setEmptyView(textView);
        //实例化SimpleCursorAdapter
        mCursorAdapter = new SimpleCursorAdapter(this, R.layout.item_listview, null, new
                String[]{"_id", "title"}, new int[]{R.id.tv_itemSummary, R.id.tv_itemDetail},
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        mListView.setAdapter(mCursorAdapter);
        //注册上下文菜单
        registerForContextMenu(mListView);
    }

    private void loadData() {
        //此时cursor中就没有id这一列了,而是_id
        String sql = "select id as _id , title ,content from android_basic order by id desc";
        //查询数据库
        Cursor cursor = mSqLiteDatabase.rawQuery(sql, null);
        mCursorAdapter.changeCursor(cursor);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_insert:
                actionInsert();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void actionInsert() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog, null);
        final EditText et_summary = (EditText) view.findViewById(R.id.et_summary);
        final EditText et_detail = (EditText) view.findViewById(R.id.et_detail);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_input_add).setTitle("添加").setView(view)
                .setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface
                .OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String summary = et_summary.getText().toString();
                String detail = et_detail.getText().toString();
                //查询数据后cursor的游标停留在-1的位置,此时取值会抛出异常,应先通过cursor.moveToNext()移动游标在进行取值
                Cursor cursor = mSqLiteDatabase.rawQuery("select max(id) from android_basic", null);
                cursor.moveToFirst();
                String columnName = cursor.getColumnName(0);
                Log.i("SQLiteDataBaseActivity", "---onClick()--->" + columnName);
                int id = cursor.getInt(0);
                cursor.close();
                String sql = "insert into android_basic (id , title , content ,importance," +
                        "showFlag, version) values(?,?,?,?,?,?)";
                mSqLiteDatabase.execSQL(sql, new String[]{String.valueOf(id + 1), summary,
                        detail, "1", "1", "1"});
                loadData();
            }
        }).show();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo
            menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.context, menu);
        //contextMenu设置icon、title
        menu.setHeaderIcon(android.R.drawable.ic_menu_info_details).setHeaderTitle("which is " +
                "your" + " choice");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        //点击的item的poition
        int position = menuInfo.position;
        //点击的item在数据库中的id
        long id = menuInfo.id;
        Cursor cursor = (Cursor) mCursorAdapter.getItem(position);
        final String word = cursor.getString(cursor.getColumnIndex("title"));
        final String detail = cursor.getString(cursor.getColumnIndex("content"));
        final int _id = cursor.getInt(cursor.getColumnIndex("_id"));
        Log.i("MainActivity", "---onContextItemSelected()--->" + "position:" + position + "\t" +
                "id:" + id + "\t" + _id);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        switch (item.getItemId()) {
            case R.id.action_delete:
                actionDelete(word, _id, builder);
                break;
            case R.id.action_update:
                actionUpdate(word, detail, _id, builder);
                break;

        }
        builder.show();
        return super.onContextItemSelected(item);
    }

    private void actionUpdate(String word, String detail, final int _id, AlertDialog.Builder
            builder) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog, null);
        final EditText et_summary = (EditText) view.findViewById(R.id.et_summary);
        final EditText et_detail = (EditText) view.findViewById(R.id.et_detail);
        et_detail.setText(word);
        et_summary.setText(String.valueOf(_id));
        builder.setIcon(android.R.drawable.ic_menu_upload).setTitle("修改" + word).setMessage
                ("What" + " do you want to do").setView(view).setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String newDetail = et_detail.getText().toString();
                String newWord = et_summary.getText().toString();
                String sql = "update android_basic set id=?,title=? where id=?";
                mSqLiteDatabase.execSQL(sql, new String[]{String.valueOf(newWord), newDetail,
                        String.valueOf(_id)});
                loadData();
            }
        });
    }

    private void actionDelete(String word, final int _id, AlertDialog.Builder builder) {
        builder.setIcon(android.R.drawable.ic_delete).setTitle("删除" + _id).setMessage("What do "
                + "you want to do").setNegativeButton("取消", null).setPositiveButton("确定", new
                DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String sql = "delete from android_basic where id=?";
                mSqLiteDatabase.execSQL(sql, new String[]{String.valueOf(_id)});
                loadData();
            }
        });
    }


}
